package com.chess.manager;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.chess.db.bean.User;
import com.chess.db.cache.UserCache;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.jfinal.kit.LogKit;
import com.sojoys.artifact.tools.ToolDate;

public class LoginTokenManager {
	/**
	 * KEY = UID
	 * VAL = Token
	 */
	static BiMap<String,String> cache = HashBiMap.create();

	public static void addCache(String uid,String token){
		cache.put(uid,token);
	}
	
	public static void updateCache(String uid,String token){
		cache.put(uid,token);
	}
	
	
	public static String removeToken(String token){
		return cache.inverse().remove(token);
	}
	
	public static void checkTimeOut(){
		Date nowDate = new Date();
		
		List<String> timeoutUids = new ArrayList<>();
		
		for (Map.Entry<String,String> e : cache.entrySet()) {
			User user = UserCache.getInstance().getById(e.getKey());
			if (ToolDate.addSecond(30, (Date) user.getLastLoginDate().clone()).before(nowDate)) {
//				removeCache(e.getKey());
				timeoutUids.add(e.getKey());
				LogKit.info("remove token = " + e.getKey());
			}
		}
		
		for (String uid : timeoutUids) {
			cache.remove(uid);
		}
	}
}
